package org.practice;

import java.util.Deque;
import java.util.LinkedList;

/**
 * @author zch
 */
public class AntiPolish {

    public static void main(String[] args) {
        String expression = "6523+8*+3+*";
        System.out.println(calculation(expression));
    }

    private static int calculation(String expression) {
        Deque<Integer> nums = new LinkedList<>();
        char[] expressionArray = expression.toCharArray();
        for (char str : expressionArray) {
            if (str >= '0' && str <= '9') {
                nums.addLast(str - '0');
            } else {
                if (nums.isEmpty() || nums.size() < 2) {
                    throw new RuntimeException("逆波兰表达式存在异常！");
                }
                int a = nums.getLast();
                nums.removeLast();
                int b = nums.getLast();
                nums.removeLast();
                switch (str) {
                    case '+':
                        nums.addLast(a + b);
                        break;
                    case '-':
                        nums.addLast(a - b);
                        break;
                    case '*':
                        nums.addLast(a * b);
                        break;
                    case '/':
                        nums.addLast(a / b);
                        break;
                    default:
                        throw new RuntimeException("逆波兰表达式存在异常！");
                }
            }
        }
        int result = nums.getLast();
        return result;
    }
}
